const { DataTypes } = require('sequelize')
const sequelize = require('../config/database')

const RolePermission = sequelize.define('RolePermission', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '权限ID'
  },
  role_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '角色ID'
  },
  template_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '权限模板ID'
  },
  permissions: {
    type: DataTypes.JSON,
    allowNull: false,
    comment: '角色权限配置（JSON格式）'
  }
}, {
  tableName: 'role_permissions',
  timestamps: true,
  indexes: [
    {
      unique: true,
      fields: ['role_id', 'template_id']
    }
  ]
})

// 与角色和模板的关联关系
const Role = require('./role')
const PermissionTemplate = require('./PermissionTemplate')

RolePermission.belongsTo(Role, {
  foreignKey: 'role_id',
  as: 'role'
})

RolePermission.belongsTo(PermissionTemplate, {
  foreignKey: 'template_id',
  as: 'template'
})

module.exports = RolePermission 